<!--
 * @Descripttion:
 * @Author: chendingfengmail@163.com
 * @version:
 * @Date: 2021-06-10 14:40:56
 * @LastEditors: chendingfengmail@163.com
 * @LastEditTime: 2022-01-17 13:58:10
-->
<template>
  <el-dialog
    :title="titleName"
    width="30%"
    center
    :visible.sync="visible"
    :before-close="modalClose"
    @open="modelOpen"
    :close-on-click-modal="false">
    <el-form
      :rules="userHandleRules"
      ref="userHandleForm"
      :model="modelData"
      :disabled="formDisabled"
      v-loading="loading">
      <el-form-item label="用户姓名" :label-width="formLabelWidth" prop="name">
        <el-input
          v-model.trim="modelData.name"
          autocomplete="off"
          maxlength="30"
          placeholder="请输入用户姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户账号" :label-width="formLabelWidth" prop="username">
        <el-input
          v-model.trim="modelData.username"
          maxlength="30"
          autocomplete="off"
          placeholder="请输入用户账号"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户密码" :label-width="formLabelWidth" v-show="passwordVisible" prop="password">
        <el-input
          v-model="modelData.password"
          autocomplete="off"
          maxlength="30"
          placeholder="请输入用户密码"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item label="用户角色" :label-width="formLabelWidth" prop="roles">
        <el-select v-model="modelData.roles" placeholder="请选择用户角色" style="width: 100%">
          <el-option v-for="(item, index) in roles" :key="index" :label="item.description" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" :label-width="formLabelWidth" prop="mobile">
        <el-input v-model="modelData.mobile" maxlength="30" autocomplete="off" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="电子邮件" :label-width="formLabelWidth" prop="email">
        <el-input v-model="modelData.email" maxlength="40" autocomplete="off" placeholder="请输入电子邮件"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" v-show="btnVisible">
      <el-button type="primary" @click="formSubmit" :loading="loading">提 交</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'userHandleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    modelType: {
      type: String,
      required: true,
      default: () => {
        return 'info';
      },
    },
    modelData: {
      type: Object,
      default: () => {
        return {
          name: '',
          relativeId: '',
          relativeName: '',
          description: '',
          reserver1: '',
          roles: '',
        };
      },
    },
  },
  watch: {
    // 'modelData.idCardType': {
    //   handler(val, oval){
    //     let msg = this.$enums.ID_CARD_TYPE.getLabelByValue(val);
    //     this.$data.userHandleRules.idCard = this.$Validate.validateIdCard(val, true, "请输入" + msg + "号码");
    //     this.modelData.idCard = "";
    //     this.$refs['userHandleForm'].clearValidate(['idCard']);
    //   }
    // }
  },
  data() {
    return {
      titleName: '详情',
      formLabelWidth: '80px',
      dialogFormVisible: false,
      formDisabled: false,
      passwordVisible: false,
      btnVisible: true,
      loading: false,

      userHandleRules: {
        name: this.$Validate.ordinaryTxt(true, '请输入用户名称'),
        username: this.$Validate.integrateTxt(true, '请输入用户账号'),
        password: this.$Validate.password(true, '请输入用户密码'),
        roles: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
        mobile: this.$Validate.mobile(true, '请输入手机号码'),
        //email: this.$Validate.email(true, '请输入电子邮件'),
      },

      roles: [],
    };
  },
  created() {},
  mounted() {},
  methods: {
    // 对话框打开
    modelOpen() {
      this.loadUserRoles();
      switch (this.modelType) {
        case 'add':
          this.modelTypeChange('用户添加', false, true, true);
          this.userHandleRules['password'] = this.$Validate.password(true, '请输入用户密码');
          break;
        case 'info':
          this.modelTypeChange('用户详情', true, false, false);
          this.getUserRole(this.modelData.username);
          break;
        case 'edit':
          this.modelTypeChange('用户编辑', false, true, false);
          this.getUserRole(this.modelData.username);
          delete this.userHandleRules.password;
          break;
        default:
          break;
      }
    },

    // 模式切换
    modelTypeChange(titleName, formDisabled, btnVisible, passwordVisible) {
      this.titleName = titleName;
      this.formDisabled = formDisabled;
      this.btnVisible = btnVisible;
      this.passwordVisible = passwordVisible;
    },

    // 表单提交
    formSubmit() {
      this.$refs.userHandleForm.validate((valid) => {
        if (valid) {
          switch (this.modelType) {
            case 'add':
              this.handleAdd(this.modelData);
              break;
            case 'edit':
              this.handleEdit(this.modelData);
              break;
            default:
              break;
          }
        }
      });
    },

    // 加载用户角色列表
    loadUserRoles() {
      let param = {
        pageIndex: 1,
        pageSize: 9999,
      };
      this.$api.userRole.findRoleList(param).then((res) => {
        this.roles = res.value;
      });
    },

    // 新增
    handleAdd(formData) {
      this.loading = true;
      this.$api.user
        .addUser(formData)
        .then((res) => {
          this.$message.success('用户添加成功');
          this.loading = false;
          this.modalClose();
          this.$emit('loadList');
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 编辑
    handleEdit(formData) {
      formData.password = undefined;
      this.loading = true;
      this.$api.user
        .updateUser(formData)
        .then((res) => {
          this.$message.success('用户更新成功');
          this.loading = false;
          this.modalClose();
          this.$emit('loadList');
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 获取用户角色
    getUserRole(username) {
      this.loading = true;
      this.$api.userRole
        .findRoleByUserName(username)
        .then((res) => {
          if (res.error === 0) {
            this.modelData.roles = res.value[0].id;
          }
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    // 重置表单
    resetForm() {
      this.$nextTick(() => {
        this.$refs.userHandleForm.resetFields();
      });
    },
    // 对话框关闭
    modalClose() {
      this.resetForm();
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
  },
};
</script>
<style lang="scss">
</style>
